package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	// 初始化 MongoDB 连接
	client, err := connectMongoDB("mongodb://101.43.132.73:27017", 5000*time.Millisecond)
	if err != nil {
		log.Fatal("Failed to connect to MongoDB:", err)
	}
	defer client.Disconnect(context.Background())

	// 在这里进行其他操作，例如执行查询或更新
	// ...

	fmt.Println("Connected to MongoDB successfully.")
}

// connectMongoDB 初始化 MongoDB 连接
func connectMongoDB(uri string, timeout time.Duration) (*mongo.Client, error) {
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
	if err != nil {
		return nil, err
	}

	// 检查连接是否建立
	err = client.Ping(ctx, nil)
	if err != nil {
		return nil, err
	}

	return client, nil
}
